

import 'dart:io';
import 'dart:ui';

import 'package:bt_tool/basic/bt_controller.dart';
import 'package:bt_tool/basic/bt_date_tool.dart';
import 'package:bt_tool/basic/bt_db_tool.dart';
import 'package:bt_tool/basic/bt_file_tool.dart';
import 'package:bt_tool/basic/bt_model.dart';
import 'package:bt_tool/basic/bt_router.dart';
import 'package:bt_tool/basic/bt_shared_preferences.dart';
import 'package:bt_tool/basic/bt_utils.dart';
import 'package:bt_tool/widget/bt_dialog_widget.dart';
import 'package:bt_tool/widget/bt_text_field.dart';
import 'package:bt_tool/widget/bt_toast.dart';
import 'package:desktop_drop/desktop_drop.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_demo/common/config/app_router.dart';
import 'package:flutter_demo/tools/imgPath/img_path_define.dart';
import 'package:get/get.dart';
import 'package:path/path.dart' as path;
import '../model/img_path_model.dart';

class ImgPathMainController extends BTController{

  var isDragFile = false.obs;
  var currentRootPath = "".obs;
  var currentFolder = "".obs;
  var dataList = <ImgPathModel>[].obs;
  var isHadPermission = false;
  var isIosStyle = true.obs;
  String lastImgName = "";

  @override
  void initState() async {
    super.initState();
    currentRootPath.value = BTSharedPreferences.get(ImgPathDefine.lastPathCacheKey, "");
    currentFolder.value = BTSharedPreferences.get(ImgPathDefine.lastFolderCacheKey, "");
    await BTDbTool.share().createTable(ImgPathDefine.tableName, [
      BTDbFieldModel("id", BTModelFieldType.intType,isAutoIncrement: true,isNotNull: true,isPrimaryKey: true),
      BTDbFieldModel("resultPath", BTModelFieldType.stringType,isNotNull: true,),
      BTDbFieldModel("imgPath_1", BTModelFieldType.stringType,isNotNull: true,),
      BTDbFieldModel("imgPath_2", BTModelFieldType.stringType,isNotNull: false,),
      BTDbFieldModel("imgName", BTModelFieldType.stringType,isNotNull: true,),
      BTDbFieldModel("time", BTModelFieldType.intType,isNotNull: true,),
      BTDbFieldModel("flutterConfigStr", BTModelFieldType.stringType,isNotNull: true,),
      BTDbFieldModel("extension", BTModelFieldType.stringType,isNotNull: true,),
      BTDbFieldModel("isIosStyle", BTModelFieldType.intType,isNotNull: false,defaultValue: "1")
    ]);
    refreshData();
  }

  refreshData() async {
    var result = await BTDbTool.share().query(ImgPathDefine.tableName,orderBy: "time DESC");
    List<ImgPathModel> list = [];
    for(var map in result){
      list.add(ImgPathModel(map));
    }
    dataList.clear();
    dataList.addAll(list);
  }


  Future<void> pickPath() async {
    final String? directoryPath = await getDirectoryPath(
      confirmButtonText: '选择文件夹',
      initialDirectory: currentRootPath.value.isEmpty ? null : currentRootPath.value,
    );
    if (directoryPath == null) {
      return;
    }
    currentRootPath.value = directoryPath;
    currentFolder.value = "";
    BTSharedPreferences.save(ImgPathDefine.lastPathCacheKey, directoryPath);
    BTSharedPreferences.save(ImgPathDefine.lastFolderCacheKey, "");
  }

  pickFolder() async {
    if(btIsStrEmpty(currentRootPath.value)){
      BTToast.showToast("请先选择根路径");
      return;
    }
    var list = await BTFileTool.getFolderInDirectory(currentRootPath.value);
    List<String> folderList = [];
    for(var folder in list){
      folderList.add(path.basename(folder.path));
    }

    if(list.isEmpty){
      BTToast.showToast("当前暂无文件夹，请先创建");
      return;
    }


    BTRouter.share().pushToUrl(
      routerUrl: AppRouterDefine.imgPathPickFolderPage,
      routerParameter: {
        "dataList" : folderList,
      },
      callback: (obj,id){
        if(id == "itemClick"){
          currentFolder.value = obj;
          BTSharedPreferences.save(ImgPathDefine.lastFolderCacheKey, obj);
        }
      }
    );
  }

  createFolder() {
    if(currentRootPath.value.isEmpty){
      BTToast.showToast("选择根路径");
      return;
    }

    final BTTextFieldController controller = BTTextFieldController();
    BTAlertInputWidget inputDialog = BTAlertInputWidget(
      isPcStyle: true,
      title: "输入图片名称",
      controller: controller,
      clickCallBack: (action) async {
        BTDialog.dismiss();
        if(action == BTAlertAction.ok){
          String name = controller.getText();
          if(name.isEmpty){
            return;
          }

          if(isIosStyle.value){
            await BTFileTool.createFolderIfNotExist(
              Directory("${currentRootPath.value}/$name/2.0x"),
              recursive: true,
            );
            await BTFileTool.createFolderIfNotExist(
              Directory("${currentRootPath.value}/$name/3.0x"),
              recursive: true,
            );
            BTToast.showToast("创建成功");
          }else{
            await BTFileTool.createFolderIfNotExist(
              Directory("${currentRootPath.value}/$name"),
              recursive: true,
            );
            BTToast.showToast("创建成功");
          }


        }
      },
    );
    BTDialog.show(inputDialog);

  }

  Future<void> importImg() async {
    if(currentRootPath.value.isEmpty){
      BTToast.showToast("选择根路径");
      return;
    }

    // if(currentFolder.value.isEmpty){
    //   BTToast.showToast("选择目标文件夹");
    //   return;
    // }

    const XTypeGroup imageGroup = XTypeGroup(
      label: 'images',
      extensions: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'heic'],
    );

    final List<XFile> files = await openFiles(
      acceptedTypeGroups: [imageGroup],
    );

    if (files.isEmpty) {
      BTToast.showToast("未选择任何文件");
      return;
    }

    List<File> fileList = [];
    for(var xFile in files){
      fileList.add(File(xFile.path));
    }
    importFile(fileList);
  }

  showInputNameDialog(ImgPathModel model){
    final BTTextFieldController controller = BTTextFieldController(
      textEditingController: TextEditingController(text: lastImgName),
    );
    BTAlertInputWidget inputDialog = BTAlertInputWidget(
      isPcStyle: true,
      title: "输入图片名称",
      controller: controller,
      clickCallBack: (action) async {
        BTDialog.dismiss();
        if(action == BTAlertAction.ok){
          String name = controller.getText();
          if(name.isEmpty){
            return;
          }

          if(!btIsStrEmpty(currentFolder.value)){
            model.flutterConfigStr = "- ${path.basename(currentRootPath.value)}/${currentFolder.value}/$name${model.extension}";
          }else{
            model.flutterConfigStr = "- ${path.basename(currentRootPath.value)}/$name${model.extension}";
          }


          model.imgName = name;
          model.time = BTDateTool.currentTimeSeconds();
          var result = await BTDbTool.share().insertData(ImgPathDefine.tableName, model.convertToDictExcept(["id"]));
          refreshData();
          model.saveImgIos();
          lastImgName = name;
        }
      },
    );
    BTDialog.show(inputDialog);
  }

  deleteFile(ImgPathModel model){
    BTAlertTextWidget textDialog = BTAlertTextWidget(
      contentStr: '是否要删除当前目标文件？',
      title: '提示',
      isPcStyle: true,
      contentAlign: TextAlign.left,
      clickCallBack: (action) async {
        BTDialog.dismiss(); //关闭对话框
        if(action == BTAlertAction.ok){
          model.deleteFile();
        }
      },
    );
    BTDialog.show(textDialog);
  }

  deleteDataAlert(ImgPathModel model){
    BTAlertTextWidget textDialog = BTAlertTextWidget(
      contentStr: '是否要删除当前内容？',
      title: '提示',
      isPcStyle: true,
      contentAlign: TextAlign.left,
      clickCallBack: (action) async {
        BTDialog.dismiss(); //关闭对话框
        if(action == BTAlertAction.ok){
          await BTDbTool.share().deleteData(ImgPathDefine.tableName,where: "id = ?",whereArgs: [model.id]);
          dataList.remove(model);
          BTToast.showToast("删除成功");
        }
      },
    );
    BTDialog.show(textDialog);
  }

  onDragDone(DropDoneDetails details) async{
    if(currentRootPath.value.isEmpty){
      BTToast.showToast("选择根路径");
      return;
    }

    // if(currentFolder.value.isEmpty){
    //   BTToast.showToast("选择目标文件夹");
    //   return;
    // }
    List<File> droppedFiles = [];
    for(var dropItem in details.files){
      if(await BTFileTool.isFile(dropItem.path)){
        droppedFiles.add(File(dropItem.path));
      }
    }
    if (droppedFiles.isEmpty) {
      BTToast.showToast("文件数量为0");
      return;
    }
    importFile(droppedFiles);
  }

  importFile(List<File> fileList){
    bool isIosScale = isIosStyle.value;
    ImgPathModel model = ImgPathModel(null);
    model.isIosStyle = isIosScale ? 1 : 0;
    if(!btIsStrEmpty(currentFolder.value)){
      model.resultPath = "${currentRootPath.value}/${currentFolder.value}";
    }else{
      model.resultPath = currentRootPath.value;
    }

    if(isIosScale){
      if(fileList.length != 2){
        BTToast.showToast("ios缩放模式只能有2张图片");
        return;
      }
      for (final file in fileList) {
        final fileName = path.basenameWithoutExtension(file.path);
        if(model.extension.isEmpty){
          model.extension = path.extension(file.path);
        }
        if(fileName.endsWith("@2x")){
          model.imgPath_1 = file.path;
        }else if(fileName.endsWith("@3x")){
          model.imgPath_2 = file.path;
        }
      }
      if(model.imgPath_1.isEmpty || model.imgPath_2.isEmpty){
        BTToast.showToast("未识别到2x或者3x图片");
        return;
      }
      showInputNameDialog(model);
    }else{
      var file = fileList.first;
      final fileName = path.basenameWithoutExtension(file.path);
      if(model.extension.isEmpty){
        model.extension = path.extension(file.path);
      }
      model.imgPath_1 = file.path;
      showInputNameDialog(model);
    }
  }

  void getPermission() async {
    if(currentRootPath.value.isEmpty){
      BTToast.showToast("当前路径为空");
      return;
    }
    final home = Platform.environment['HOME']; // /Users/mini2021
    final desktop = '$home/Desktop';
    final String? directoryPath = await getDirectoryPath(
      confirmButtonText: '选择此文件夹',
      initialDirectory: desktop, // 可选
    );
    if (directoryPath == null) {
      return;
    }
    isHadPermission = true;
    updateWidget();
  }

  void editName(ImgPathModel model){
    final BTTextFieldController controller = BTTextFieldController(
      textEditingController: TextEditingController(text: model.imgName),
    );
    BTAlertInputWidget inputDialog = BTAlertInputWidget(
      isPcStyle: true,
      title: "输入图片名称",
      controller: controller,
      clickCallBack: (action) async {
        BTDialog.dismiss();
        if(action == BTAlertAction.ok){
          String name = controller.getText();
          if(name.isEmpty){
            return;
          }
          model.flutterConfigStr = model.flutterConfigStr.replaceAll(model.imgName, name);
          model.imgName = name;
          BTDbTool.share().update(
              ImgPathDefine.tableName,
              {"imgName" : model.imgName,"flutterConfigStr" : model.flutterConfigStr},
              where: "id = ?",
              whereArgs: [model.id]
          );
          dataList.refresh();
        }
      },
    );
    BTDialog.show(inputDialog);
  }

  void copy(ImgPathModel model){
    Clipboard.setData(ClipboardData(text: model.flutterConfigStr));
    BTToast.showToast("已复制");
  }

}